using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Interactivity;
using Seems.SL.VM;

namespace Seems.View.Behaviors
{
	/// <summary>
	/// Drags the parent, contained in datacontext object, over the underlying canvas
	/// </summary>
	public class DragElementBehavior : Behavior<Thumb>
	{
		protected override void OnAttached()
		{
			base.OnAttached();
			AssociatedObject.DragStarted += MakeScreenSelected;
			AssociatedObject.DragDelta += DragDelta;
		}

		private ElementShownOnDiagramVM VM { get { return (ElementShownOnDiagramVM) AssociatedObject.DataContext; } }

		private void MakeScreenSelected(object sender, DragStartedEventArgs e)
		{
			VM.ReceiveSelection();
		}

		protected override void OnDetaching()
		{
			AssociatedObject.DragDelta -= DragDelta;
		}

		private void DragDelta(object sender, DragDeltaEventArgs e)
		{
			double x = VM.Position.X;
			double y = VM.Position.Y;
			if (double.IsNaN(x))
				x = 0;
			if (double.IsNaN(y))
				y = 0;
			double newX = Math.Max(x + e.HorizontalChange, 0);
			double newY = Math.Max(y + e.VerticalChange, 0);
			VM.Position = new Point(newX, newY);
		}
	}
}